package com.haixiaoke.saas.manage.role.controller;

import com.haixiaoke.saas.common.annotation.Log;
import com.haixiaoke.saas.common.constant.UserConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.domain.entity.SysMenu;
import com.haixiaoke.saas.common.core.page.TableDataInfo;
import com.haixiaoke.saas.common.enums.BusinessType;
import com.haixiaoke.saas.common.utils.StringUtils;
import com.haixiaoke.saas.common.utils.poi.ExcelUtil;
import com.haixiaoke.saas.dept.domain.BizDept;
import com.haixiaoke.saas.dept.service.IBizDeptService;
import com.haixiaoke.saas.role.domain.BizRole;
import com.haixiaoke.saas.role.service.IBizRoleMenuService;
import com.haixiaoke.saas.role.service.IBizRoleService;
import com.haixiaoke.saas.system.BaseController;
import com.haixiaoke.saas.system.domain.LoginUser;
import com.haixiaoke.saas.system.framework.web.service.SysPermissionService;
import com.haixiaoke.saas.system.framework.web.service.TokenService;
import com.haixiaoke.saas.system.service.ISysMenuService;
import com.haixiaoke.saas.user.domain.BizUserBusiness;
import com.haixiaoke.saas.user.domain.BizUserRole;
import com.haixiaoke.saas.user.service.IBizUserBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 企业端角色信息Controller
 *
 * @author panda
 * @date 2023-12-29
 */
@RestController
@RequestMapping("/manage/role/role")
public class ManageBizRoleController extends BaseController {
    @Autowired
    private IBizRoleService bizRoleService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private IBizUserBusinessService iBizUserBusinessService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IBizDeptService iBizDeptService;
    @Autowired
    private IBizRoleMenuService iBizRoleMenuService;
    @Autowired
    private ISysMenuService menuService;


    /**
     * 查询企业端角色信息列表
     */
    @PreAuthorize("@ss.hasPermi('manage:role:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizRole bizRole) {
        startPage();
        List<BizRole> list = bizRoleService.selectRolePage(bizRole);
        return getDataTable(list);
    }

    /**
     * 查询后端创建的企业端角色信息列表
     */
    @GetMapping("/listByManage")
    public AjaxResult roleList(BizRole bizRole) {
        List<BizRole> list = bizRoleService.selectRoleList(bizRole);
        return success(list);
    }

    /**
     * 导出企业端角色信息列表
     */
    @PreAuthorize("@ss.hasPermi('manage:role:export')")
    @Log(title = "企业端角色信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizRole bizRole) {
        List<BizRole> list = bizRoleService.selectBizRoleList(bizRole);
        ExcelUtil<BizRole> util = new ExcelUtil<BizRole>(BizRole.class);
        util.exportExcel(response, list, "角色数据");
    }

    /**
     * 获取企业端角色信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('manage:role:query')")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable("roleId") Long roleId) {
        bizRoleService.checkRoleDataScope(roleId);
        return success(bizRoleService.selectBizRoleByRoleId(roleId));
    }

    /**
     * 新增企业端角色信息
     */
    @PreAuthorize("@ss.hasPermi('manage:role:add')")
    @Log(title = "企业端角色信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizRole bizRole) {
        if (!bizRoleService.checkRoleNameUnique(bizRole)) {
            return error("新增角色'" + bizRole.getRoleName() + "'失败，角色名称已存在");
        } else if (!bizRoleService.checkRoleKeyUnique(bizRole)) {
            return error("新增角色'" + bizRole.getRoleName() + "'失败，角色权限已存在");
        }
        bizRole.setCreateBy(getUsername());
        return toAjax(bizRoleService.insertBizRole(bizRole));
    }

    /**
     * 修改企业端角色信息
     */
    @PreAuthorize("@ss.hasPermi('manage:role:edit')")
    @Log(title = "企业端角色信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizRole bizRole) {
        bizRoleService.checkRoleDataScope(bizRole.getRoleId());
        if (!bizRoleService.checkRoleNameUnique(bizRole)) {
            return error("修改角色'" + bizRole.getRoleName() + "'失败，角色名称已存在");
        } else if (!bizRoleService.checkRoleKeyUnique(bizRole)) {
            return error("修改角色'" + bizRole.getRoleName() + "'失败，角色权限已存在");
        }
        bizRole.setUpdateBy(getUsername());

        if (bizRoleService.updateBizRole(bizRole) > 0) {
            // 更新缓存用户权限
            LoginUser loginUser = getLoginUser();
            if (StringUtils.isNotNull(loginUser.getBizUser())) {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getBizUser(), loginUser.getTenantId()));
                loginUser.setBizUser(iBizUserBusinessService.selectBizUserBusinessByUserName(loginUser.getBizUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return success();
        }
        return error("修改角色'" + bizRole.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('manage:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody BizRole role) {
        bizRoleService.checkRoleDataScope(role.getRoleId());
        return toAjax(bizRoleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('manage:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody BizRole role) {
        bizRoleService.checkRoleDataScope(role.getRoleId());
        role.setUpdateBy(getUsername());
        return toAjax(bizRoleService.updateRoleStatus(role));
    }

    /**
     * 删除企业端角色信息
     */
    @PreAuthorize("@ss.hasPermi('manage:role:remove')")
    @Log(title = "企业端角色信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleId}")
    public AjaxResult remove(@PathVariable("roleId") Long roleId) {
        if (bizRoleService.checkRoleExistUser(roleId)){
            return warn("角色已关联用户，请解除后再删除");
        }
        return toAjax(bizRoleService.deleteBizRoleByRoleId(roleId));
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@ss.hasPermi('manage:role:query')")
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        return success(bizRoleService.selectRoleAll());
    }

    /**
     * 查询已分配用户角色列表
     */
    @PreAuthorize("@ss.hasPermi('manage:role:list')")
    @GetMapping("/authUser/allocatedList")
    public TableDataInfo allocatedList(BizUserBusiness user) {
        startPage();
        List<BizUserBusiness> list = iBizUserBusinessService.selectAllocatedList(user);
        return getDataTable(list);
    }

    /**
     * 查询未分配用户角色列表
     */
    @PreAuthorize("@ss.hasPermi('manage:role:list')")
    @GetMapping("/authUser/unallocatedList")
    public TableDataInfo unallocatedList(BizUserBusiness user) {
        startPage();
        List<BizUserBusiness> list = iBizUserBusinessService.selectUnallocatedList(user);
        return getDataTable(list);
    }

    /**
     * 取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('manage:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public AjaxResult cancelAuthUser(@RequestBody BizUserRole userRole) {
        return toAjax(bizRoleService.deleteAuthUser(userRole));
    }

    /**
     * 批量取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('manage:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds) {
        return toAjax(bizRoleService.deleteAuthUsers(roleId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @PreAuthorize("@ss.hasPermi('manage:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public AjaxResult selectAuthUserAll(Long roleId, Long[] userIds) {
        bizRoleService.checkRoleDataScope(roleId);
        return toAjax(bizRoleService.insertAuthUsers(roleId, userIds));
    }

    /**
     * 获取对应角色部门树列表
     */
    @PreAuthorize("@ss.hasPermi('manage:role:query')")
    @GetMapping(value = "/deptTree/{roleId}")
    public AjaxResult deptTree(@PathVariable("roleId") Long roleId) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", iBizDeptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", iBizDeptService.buildTreeList(new BizDept()));
        return ajax;
    }

    /**
     * 新增企业端角色信息
     */
    @PreAuthorize("@ss.hasPermi('manage:role:add')")
    @Log(title = "企业端角色信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult roleAdd(@RequestBody BizRole bizRole) {
        if (!bizRoleService.checkManageRoleName(bizRole)) {
            return error("新增角色'" + bizRole.getRoleName() + "'失败，角色名称已存在");
        }else if (!bizRoleService.checkRoleKeyUnique(bizRole)) {
            return error("新增角色'" + bizRole.getRoleName() + "'失败，角色权限已存在");
        }
        bizRole.setCreateBy(getUsername());
        return toAjax(bizRoleService.insertRole(bizRole));
    }

    /**
     * 修改企业端角色信息
     */
    @PreAuthorize("@ss.hasPermi('manage:role:edit')")
    @Log(title = "企业端角色信息", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult roleEdit(@RequestBody BizRole bizRole) {
        if (!bizRoleService.checkManageRoleName(bizRole)) {
            return error("修改角色'" + bizRole.getRoleName() + "'失败，角色名称已存在");
        }else if (!bizRoleService.checkRoleKeyUnique(bizRole)) {
            return error("修改角色'" + bizRole.getRoleName() + "'失败，角色权限已存在");
        }
        bizRole.setUpdateBy(getUsername());

        /*if (bizRoleService.updateBizRole(bizRole) > 0) {
            // 更新缓存用户权限
            LoginUser loginUser = getLoginUser();
            if (StringUtils.isNotNull(loginUser.getBizUser())) {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getBizUser()));
                loginUser.setBizUser(iBizUserBusinessService.selectBizUserBusinessByUserName(loginUser.getBizUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return success();
        }*/
//        return error("修改角色'" + bizRole.getRoleName() + "'失败，请联系管理员");
        return toAjax(bizRoleService.updateBizRole(bizRole));
    }

    /**
     * 查询该角色的菜单权限与所有菜单--树状结构
     */
    @PreAuthorize("@ss.hasPermi('system:menu:list')")
    @GetMapping("/roleMenuTreeselect/{roleId}")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        if (roleId == null) {
            return error("角色数据异常");
        }
        List<SysMenu> sysMenus = bizRoleService.selectMenuList(roleId, UserConstants.SERVER_OWNER_ENTERPRISE);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("menuIdsByRole",iBizRoleMenuService.selectMenuIdsByRoleId(roleId));
        ajax.put("menus",menuService.buildMenuTreeSelect(sysMenus));
        return ajax;
    }

    /**
     * 设置角色权限菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:edit')")
    @PutMapping("/editMenuByRole")
    public AjaxResult editMenuByRole(@RequestBody BizRole role) {
        if (StringUtils.isNull(role.getRoleId()) || StringUtils.isEmpty(role.getMenuIds())) {
            return AjaxResult.error("菜单数据缺失");
        }
        return toAjax(bizRoleService.editMenuByRole(role));
    }

    /**
     * 查询该角色的数据权限范围
     */
    @PreAuthorize("@ss.hasPermi('manage:role:list')")
    @GetMapping("/permissionSelect/{roleId}")
    public AjaxResult permissionSelect(@PathVariable("roleId") Long roleId) {
        if (roleId == null) {
            return error("角色数据异常");
        }
        return success(bizRoleService.selectPermissionByRoleId(roleId));
    }

    /**
     * 设置数据权限
     */
    @PreAuthorize("@ss.hasPermi('manage:role:edit')")
    @Log(title = "企业端角色信息", businessType = BusinessType.UPDATE)
    @PutMapping("/editPermission")
    public AjaxResult editPermission(@RequestBody BizRole bizRole) {
        return toAjax(bizRoleService.updateRolePermission(bizRole));
    }
}
